<?php

namespace App\Console\Commands;

use App\Http\Models\Mysql\StyleTable;
use App\Http\Repository\CommonRepository;
use App\Http\Services\Banshi\DesignService;
use Illuminate\Console\Command;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class downloadBom extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:downloadBom {--year=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导出excel 大货BOM清单';

    protected $_cellName = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $year = $this->option("year") ?? "2024";
        $filename = "十三余_大货BOM清单_{$year}.xls";
        $file = storage_path("cache/").$filename;
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        $header = [
            ['number','款号'],
            ['creator','创建人'],
            ['new_date','上新月份'],
            ['materiel_img','物料图片'],
            ['materiel_major_category','物料类型'],
            ['materiel_minor_category', '物料分类'],
            ['materiel', '物料名称'],
            ['part', '部位'],
            ['materiel_attribute', '属性'],
            ['color_value', '单色专用'],
            ['materiel_major_unit', '单位'],
            ['amount', '用料详情'],
            ['price', '大货单价'],
            ['supplier', '供应商']
        ];
        foreach($header as $index => $item){
            $sheet->setCellValue($this->_cellName[$index]."1", $item[1]);
            $sheet->getStyle($this->_cellName[$index]."1")->applyFromArray([
                'fill' => [
                    'fillType' => Fill::FILL_SOLID,
                    'startColor' => [
                        'argb' => Color::COLOR_BLACK,
                    ],
                ],
                'font' => [
                    'color' => [
                        'argb' => Color::COLOR_WHITE,
                    ],
                ]
            ]);
            $sheet->getColumnDimension($this->_cellName[$index])->setWidth('20');
        }
        $numIndex = 2;
        $list = (new StyleTable())->where('approval_state', '<>', 4)->where('year', $year)->where('brand_id', 1)
            //->where('number', 'STP186334')
            ->orderBy("year", "desc")->orderBy("month", "desc")->orderBy("creation_time", "desc")->get(['id', 'number', 'creator', 'year', 'month'])->toArray();
        $total = count($list);
        foreach ($list as $sIndex => $style){
            $bomList = (new DesignService())->detailMaterial($style['id'], 1);
            echo "正在写入: {$year}年上新 [{$total}, ".($sIndex+1)."] {$style['number']} \n";
            foreach ($bomList as $bom) {
                //属性
                $materielAttribute = "";
                $materielAttributeList = json_decode($bom['materiel_attribute'], true);
                foreach ($materielAttributeList as $item){
                    $materielAttribute = $materielAttribute.(!empty($materielAttribute) ? ", ":"").$item['name'].":".$item['value'];
                }
                $colorCode = "#fff";
                if(isset($bom['style_bom_colour_config'][0][0]['code']) && $bom['style_bom_colour_config'][0][0]['code'] != ""){
                    $colorCode = CommonRepository::getColor($bom['style_bom_colour_config'][0][0]['code']);
                }
                $data = [
                    'number' => $style['number'],
                    'creator' => $style['creator'],
                    'new_date' => $style['year']."-".$style['month'],
                    'materiel_img' => $bom['img'],
                    'materiel_major_category' => $bom['materiel_major_category'],//物料类型
                    'materiel_minor_category' => $bom['materiel_minor_category'],//物料分类
                    'materiel' => $bom['materiel'],//物料名称
                    'part' => $bom['part'],//部位,
                    'materiel_attribute' => $materielAttribute,//属性
                    'color_value' => $bom['style_bom_colour_config'][0][0]['value'] ?? "",//单色专用
                    'color_code' => $colorCode,//单色专用
                    'materiel_major_unit' => $bom['materiel_major_unit'],//单位
                    'amount' => round($bom['style_bom_size_config']['amount'] ?? 0, 3),//用料详情
                    'price' => round($bom['price'], 3),//大货单价
                    'supplier' => $bom['supplier'],//供应商
                ];
                foreach ($header as $hIndex => $hItem){
                    $sheet->setCellValue($this->_cellName[$hIndex].$numIndex, $data[$hItem[0]]);
                    if($hItem[0] == 'color_value' && !empty($data[$hItem[0]])){
                        $sheet->getStyle($this->_cellName[$hIndex].$numIndex)->applyFromArray([
                            'fill' => [
                                'fillType' => Fill::FILL_SOLID,
                                'startColor' => [
                                    'argb' => str_replace("#", "", $data['color_code']),
                                ],
                            ],
                        ]);
                    }
                }
                $numIndex++;
            }
        }
        // 保存Excel文件
        (new Xlsx($spreadsheet))->save($file);
        die("处理结束！！！");
    }
}
